#!/bin/sh
# Translates a DBus interface name (e.g. org.freedesktop.ModemManager.Modem) to a C++
# header name (mm-modem.h).

translate () {
	local oldprefix="$1"
	local ifempty="$2"
	local filename="$3"

	# If the name ends with '.xml', strip it.
	# If the name begins with <old-prefix>, strip it.
	# If the name begins with a leading dot, strip it.
	filename=$(echo "$filename" | sed -e 's/\.xml$//' \
                                          -e "s/^$oldprefix//" \
                                          -e 's/^\.//')

	# Lowercase, replace all dots with dashes.
	filename=$(echo "$filename" | tr A-Z. a-z-)

	# If the name is empty, replace it with ifempty.
	[ -z "$filename" ] && filename="$ifempty"

	filename="${filename}_server_glue.h"
	echo "$filename"
}

runonetest () {
	echo "'$1' '$2' '$3' -> "
	local res=$(translate "$@")
	echo "   Got: $res"
	echo "  Want: $4"
	if [ "$res" != "$4" ]; then
		exit 1
	fi
}

runtest () {
	runonetest "org.foo.Bar" "quxx" "org.foo.Bar.Quzz.xml" \
	    "quzz_server_glue.h"
	runonetest "org.foo.Bar" "quxx" "org.foo.Bar.xml" \
	    "quxx_server_glue.h"
	runonetest "org.foo.Bar" "quxx" "baz-hax.xml" \
	    "baz-hax_server_glue.h"
	runonetest "\(org.foo.Bar\|org.foo.Baz\)" "quxx" "org.foo.Bar.Abc.xml" \
	    "abc_server_glue.h"
	runonetest "\(org.foo.Bar\|org.foo.Baz\)" "quxx" "org.foo.Baz.Def.xml" \
	    "def_server_glue.h"
	echo "All OK."
}

usage () {
	echo "Usage: $0 <old-prefix> <if-empty> <filename>"
	echo "       $0 --test"
}

if [ $# -eq 1 -a "$1" == "--test" ]; then
	runtest
elif [ $# -eq 3 ]; then
	translate "$@"
else
	usage
	exit
fi
